import fnmatch
import polib
import os, sys
from functools import wraps
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, Response, current_app
from flaskext.babel import Babel

app = Flask(__name__)
babel = Babel(app)

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == app.config["USER"] and app.config["PASSWORD"]

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if app.config["USER"]:
            auth = request.authorization
            if not auth or not check_auth(auth.username, auth.password):
                return authenticate()
        return f(*args, **kwargs)
    return decorated


def list_pofiles():
    flist = []
    pattern = '*.po'
    for root, dirs, files in os.walk(app.config["PO_PATH"]):
        for filename in fnmatch.filter(files, pattern):
            flist.append( os.path.join(root, filename) )   
    return flist 

@app.route('/')
@requires_auth
def index():
    #cur = g.db.execute('select title, text from entries order by id desc')
    #entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    #return render_template('show_entries.html', entries=entries)
    return render_template('index.html', files=list_pofiles())
    
@app.route('/edit/<int:index>',methods=["POST","GET"])
@requires_auth
def show_po(index):
    files=list_pofiles()
    filename=files[index]
    po = polib.pofile(filename)
    entries = po.untranslated_entries()+po.fuzzy_entries()+po.translated_entries()+po.obsolete_entries()
    if request.method=="POST":
        for i, e in enumerate(entries):
            if e.obsolete: continue
            e.msgstr = request.form.get("e"+str(i))
            e.comment = request.form.get("c"+str(i))  
            if request.form.get("f"+str(i)):
                if "fuzzy" not in e.flags: e.flags.append("fuzzy")
            else:
                if "fuzzy" in e.flags: e.flags.remove("fuzzy")
        po.save()
        
        if current_app.config["AUTOCOMPILE"]:
            base,ext=os.path.splitext(filename)
            po.save_as_mofile(base+".mo")
            
        if app.config["SAVE_CALLBACK"] is not None: os.system(current_app.config["SAVE_CALLBACK"])
            
        return redirect(url_for(".index"))      
    return render_template('po.html', filename=filename, po=po, entries=entries)    
    
@app.route('/')
def show_entries():
    #cur = g.db.execute('select title, text from entries order by id desc')
    #entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]
    #return render_template('show_entries.html', entries=entries)
    
    return render_template('index.html', files=list_pofiles())


